package cn.myframe.task.quartz;

import cn.myframe.entity.sys.SysLogConfig;
import cn.myframe.entity.sys.SysLogConfig.LogBackupType;
import cn.myframe.entity.sys.SysLogEntity;
import cn.myframe.service.sys.SysLogService;
import cn.myframe.utils.DateUtils;
import cn.myframe.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component("logBackupSchedule")
public class LogBackup {
	private static final Logger LOGGER =  LoggerFactory.getLogger(LogBackup.class);
	
	@Autowired
	private SysLogService sysLogService;
	
	public void logBackup(){
		System.out.println("======================日志备份开始=============================");
		LOGGER.debug("日志自动备份开始！！！");
		SysLogConfig sysLogConfig = sysLogService.querySysLogConfig();
		SysLogEntity sysLog = new SysLogEntity();
		if(sysLogConfig == null){
			Date resultDate = DateUtils.addMonths(new Date(),-1);
			sysLog.setCreateDate(resultDate);
		}else{
			switch (LogBackupType.getType(sysLogConfig.getLogBackupType())) {
			case A_MONTH_AGO:
				sysLog.setCreateDate(DateUtils.addMonths(new Date(),-1));
				break;
			case THREE_MONTH_AGO:
				sysLog.setCreateDate(DateUtils.addMonths(new Date(),-3));
				break;
			case HALF_YEAR_AGO:
				sysLog.setCreateDate(DateUtils.addMonths(new Date(),-6));
				break;
			case A_YEAR_AGO:
				sysLog.setCreateDate(DateUtils.addMonths(new Date(),-12));
				break;
			case TWO_YEAR_AGO:
				sysLog.setCreateDate(DateUtils.addMonths(new Date(),-24));
				break;
			default:
				sysLog.setCreateDate(DateUtils.addMonths(new Date(),-1));
				break;
		}
		List<SysLogEntity> rslist = sysLogService.queryBackupLogs(sysLog);
		if (rslist != null && rslist.size() > 0) {
			//String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
			String path = sysLogConfig.getLogBackupPath().trim();
            String fileName = DateUtils.format(rslist.get(rslist.size()-1).getCreateDate(), "yyyy-MM-dd") + "_" 
            + DateUtils.format(rslist.get(0).getCreateDate(), "yyyy-MM-dd") + ".txt";
            StringBuffer content = new StringBuffer();
            content.append("用户账号,用户操作,请求方法,请求参数,IP,创建时间,日志类型" + System.getProperty("line.separator"));
            int count = 0;
            try {
				for (SysLogEntity log : rslist) {
				    content.append(log.getUsername() + "," + log.getOperation() + "," + log.getMethod() + "," + log.getParams()
				            + "," + log.getIp() + "," + DateUtils.format(log.getCreateDate(),"yyyy-MM-dd HH:mm:ss") + ",");
				    switch (log.getType()) {
					case 1:
						content.append("登陆日志");
						break;
					case 2:
						content.append("操作日志");
						break;
					default:
						content.append("错误日志");
						break;
					}
				    content.append(System.getProperty("line.separator"));
				    if (count != 0 && count % 1000 == 0) {
				        FileUtils.newStaticFile(path, fileName, content.toString(),1024*8 ,true);
				        content = new StringBuffer();
				    }
				    count++;
				}
				boolean result = FileUtils.newStaticFile(path, fileName, content.toString(),1024*8, true);
				// 删除相应记录
				if(result){
					this.sysLogService.deleteByEntity(sysLog);
					LOGGER.debug("日志自动备份成功！！！");
				}
			} catch (Exception e) {
				LOGGER.error("日志自动备份失败！！！");
				e.printStackTrace();
			}
        }
		System.out.println("======================日志自动备份结束=============================");
    }
  }
}
